import { ethers } from 'ethers';

export interface NetworkConfig {
  name: string;
  chainId: number;
  rpcUrl: string;
  blockExplorer: string;
  nativeCurrency: {
    name: string;
    symbol: string;
    decimals: number;
  };
}

export class NetworkManager {
  private networks: NetworkConfig[] = [
    {
      name: 'Ethereum Mainnet',
      chainId: 1,
      rpcUrl: 'https://mainnet.infura.io/v3/YOUR_INFURA_KEY',
      blockExplorer: 'https://etherscan.io',
      nativeCurrency: {
        name: 'Ethereum',
        symbol: 'ETH',
        decimals: 18
      }
    },
    {
      name: 'Polygon',
      chainId: 137,
      rpcUrl: 'https://polygon-rpc.com',
      blockExplorer: 'https://polygonscan.com',
      nativeCurrency: {
        name: 'Polygon',
        symbol: 'MATIC',
        decimals: 18
      }
    },
    {
      name: 'BSC',
      chainId: 56,
      rpcUrl: 'https://bsc-dataseed.binance.org',
      blockExplorer: 'https://bscscan.com',
      nativeCurrency: {
        name: 'BNB',
        symbol: 'BNB',
        decimals: 18
      }
    },
    {
      name: 'Arbitrum',
      chainId: 42161,
      rpcUrl: 'https://arb1.arbitrum.io/rpc',
      blockExplorer: 'https://arbiscan.io',
      nativeCurrency: {
        name: 'Ethereum',
        symbol: 'ETH',
        decimals: 18
      }
    }
  ];

  private currentNetwork: NetworkConfig = this.networks[0];

  // 获取所有网络
  getNetworks(): NetworkConfig[] {
    return this.networks;
  }

  // 获取当前网络
  getCurrentNetwork(): NetworkConfig {
    return this.currentNetwork;
  }

  // 切换网络
  switchNetwork(network: NetworkConfig): void {
    this.currentNetwork = network;
  }

  // 根据链ID获取网络
  getNetworkByChainId(chainId: number): NetworkConfig | undefined {
    return this.networks.find(network => network.chainId === chainId);
  }

  // 添加自定义网络
  addCustomNetwork(network: NetworkConfig): void {
    const existingNetwork = this.networks.find(n => n.chainId === network.chainId);
    if (!existingNetwork) {
      this.networks.push(network);
    }
  }

  // 获取网络提供商
  getProvider(): ethers.JsonRpcProvider {
    return new ethers.JsonRpcProvider(this.currentNetwork.rpcUrl);
  }

  // 检查网络连接
  async checkNetworkConnection(): Promise<boolean> {
    try {
      const provider = this.getProvider();
      await provider.getBlockNumber();
      return true;
    } catch (error) {
      console.error('网络连接失败:', error);
      return false;
    }
  }

  // 获取Gas价格
  async getGasPrice(): Promise<string> {
    try {
      const provider = this.getProvider();
      const gasPrice = await provider.getFeeData();
      return gasPrice.gasPrice?.toString() || '0';
    } catch (error) {
      console.error('获取Gas价格失败:', error);
      return '0';
    }
  }

  // 估算Gas限制
  async estimateGas(to: string, value: string, data?: string): Promise<string> {
    try {
      const provider = this.getProvider();
      const gasEstimate = await provider.estimateGas({
        to,
        value: ethers.parseEther(value),
        data
      });
      return gasEstimate.toString();
    } catch (error) {
      console.error('估算Gas失败:', error);
      return '21000'; // 默认Gas限制
    }
  }
}
